
<!--  -->
<template>
  <el-container>
    <el-header height="48px" class="header_wrapper">
      <span class="header_wrapper--title">{{ title }}</span>
      <span class="header_wrapper--codeName">{{ _itemCode }}</span>
      <div v-if="!isLookTask" class="header_wrapper--btngroup">
        <el-button
          v-if="topPermissions || topNextPermissions"
          size="small"
          type="primayr"
          @click="clickAddMainTask "
        >添加里程碑</el-button>
        <el-button
          v-if="topPermissions || topNextPermissions"

          size="small"
          plain
          type="primary"
          @click="clickReferTemplate"
        >引用模板</el-button>
      </div>

      <el-button
        style="margin-left: 24px"
        size="small"
        plain
        type="primary"
        @click="clickSaveTemplate"
      >保存模板</el-button>
    </el-header>
    <el-main>
      <el-table
        :data="resizeTaskList"
        height="99%"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children' }"
        size="mini"
        :indent="0"
        append-to-body
        :row-style="rowStyle"
        :default-sort="{ prop: 'indexNum', order: 'ascending' }"
        :cell-style="{ color: '#2D405E' }"
      >
        <el-table-column prop="indexNum" label="序号" width="auto" />
        <el-table-column
          v-for="v in renderTableConfig"
          :key="v.id"
          :show-overflow-tooltip="v.overflow ? true : false"
          :prop="v.property"
          :formatter="v.formatter ? v.formatter : null"
          :label="v.label"
          :min-width="v.w"
          :align="v.align ? v.align : 'center'"
          :cell-style="tableStyle.cellStyle"
        >
          <template v-if="v.slot" #default="{ row }">
            <!-- 引用为1 未引用0 -->
            <!-- 任务编辑 || 添加 -->
            <template v-if="topPermissions">
              <span v-for="s in v.childs" :key="s.code" style="margin: 0 3px">
                <template v-if="row.quoteId === 1 ">
                  <template v-if="!['edit','del'].includes(s.code)">
                    <el-button
                      type="text"
                      @click="options(s.code, row)"
                    >{{ row.parentId ?'添加子任务':'添加任务' }}
                    </el-button>
                  </template>
                </template>
                <template v-else>

                  <el-button
                    type="text"
                    @click="options(s.code, row)"
                  >
                    {{ s.code =='add' ? (row.parentId ?'添加子任务':'添加任务') :s.name }}
                  </el-button>
                </template>
              </span>
            </template>
            <template v-else>
              <span v-for="s in row.btns" :key="s.code" style="margin: 0 3px">
                <el-button
                  type="text"
                  @click="options(s.code, row)"
                >{{ s.code =='add' ? (row.parentId ?'添加子任务':'添加任务') :s.name }}
                </el-button>
              </span>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer class="footer_wrapper">
      <el-button size="mini" type="primary" @click="clickBackItem">
        返回项目
      </el-button>
      <el-button
        v-if="handleTitle === '确认' && showSubmit"
        type="primary"
        size="mini"
        @click="clickConfirmResult"
      >提交</el-button>
    </el-footer>
  </el-container>
</template>

<script>
import { mixins_base, mixins_task, } from '@/minxins/project';
import ProjectAPI from '@/apis/project';
import { mapGetters, mapState, } from 'vuex';
import { member, stringifyToArr, } from '@/filters';
import processTimeLine from '../../components/panels/childComponents/perojectInfo/processTimeLine.vue';
import moment from 'moment';
import _ from 'lodash';
import tableStyle from '../../style/table';
import { tableCellIconData, } from '../../common';
import Attachment from '@/views/project/components/attachment/attachment.vue';
import Text from '@/views/project/components/text/text.vue';
import dialogWidth from '@/views/project/common/width/dialog';

const icons = {
  file: require('@/assets/project/icons/file.svg'),
};
export default {
  name: 'TaskTableDialog',
  components: {
    // eslint-disable-next-line vue/no-unused-components
    ReferTemplate: () => import('./referTemplate.vue'),
    // eslint-disable-next-line vue/no-unused-components
    SaveTemplate: () => import('./saveTemplate.vue'),
    // eslint-disable-next-line vue/no-unused-components
    TaskMain: () => import('./taskMain.vue'),
    // eslint-disable-next-line vue/no-unused-components
    TaskChild: () => import('./taskChild.vue'),
  },
  mixins: [mixins_base, mixins_task],
  props: {
    handleTitle: {
      type: String,
      default: '',
    },
    time: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      tableStyle,
    };
  },

  computed: {
    ...mapGetters(['userInfo']),
    ...mapState('project/index', ['taskPermissionName']),
    resizeTaskList() {
      const cloneList = _.cloneDeep(this.taskTreeList);
      const cbChild = function (list, btns) {
        if (list && list.length) {
          for (const i of list) {
            Object.assign(i, { btns, });
            if (i.children && i.children.length) {
              cbChild(i.children, btns);
            }
          }
        }
      };
      // 谁创建 + 谁负责  就可以删除
      // 项目负责人 +  创建人  => 编辑项目 + （添加、删除、修改）里程碑 +  （添加、编辑、删除）任务 + （添加、删除、编辑）子任务
      // 项目参与人=> （添加）里程碑  + （添加）任务 > 谁创建+谁负责 （删除、编辑）任务。并可以（添加、修改、删除）该任务下的所有子任务

      const cb = function (list) {
        if (list && list.length) {
          for (const i of list) {
            if ([i.principal, i.createUser].indexOf(this.userInfo.id) > -1) {
              const btns = [{
                name: '编辑',
                code: 'edit',
              },
              {
                name: '删除',
                code: 'del',

              },
              {
                name: '添加任务',
                code: 'add',
              }];
              cbChild(i.children, btns);
              Object.assign(i, { btns, });
            } else if (i.userIds && i.userIds.indexOf(this.userInfo.id) > -1) {
              const btns = [{
                name: '编辑',
                code: 'edit',
              },
              {
                name: '添加子任务',
                code: 'add',
              }];
              Object.assign(i, { btns, });
            } else {
              let btns = [];
              if (this.topNextPermissions) {
                btns = [{
                  name: '添加任务',
                  code: 'add',
                }];
              } else {
                btns = [];
              }
              Object.assign(i, { btns, });
              cb(i.children, btns);
            }
          }
        }
      }.bind(this);

      cb(cloneList);
      return cloneList;
    },
    topPermissions() {
      return this.taskPermissionName.includes('leader');
    },
    topNextPermissions() {
      return this.taskPermissionName.includes('join');
    },

    title() {
      if (this.handleTitle) {
        return this.handleTitle;
      }
      if (this.isLookTask) {
        return '查看任务';
      }
      return '编辑任务';
    },
    _itemCode() {
      if (this.itemCode) {
        return `需求编号:${this.itemCode}`;
      }
      return '';
    },
    showSubmit() {
      return Number(this.researchInfo.principal) === Number(this.userInfo.id);
    },

    tableConfig() {
      return [
        {
          label: '任务名称',
          property: 'name',
          align: 'left',
          w: '160px',
          overflow: false,
          formatter: (v) => {
            let tag = null;
            let quto = null;
            if (v['isHinge']) {
              tag = this.$createElement('i', {
                domProps: {
                  innerHTML: '*',
                },
                style: { color: 'rgb(212, 16, 16)', fontWeight: 600, fontSize: ' 14px', fontStyle: 'initial', marginRight: '10px', },
              });
            }
            if (v['quoteId']) {
              quto = this.$createElement('i', {
                domProps: {
                  innerHTML: '引',
                },
                style: {
                  color: 'rgb(29 163 64)',
                  fontSize: '14px',
                  fontStyle: 'initial',
                  marginRight: '10px',
                  display: 'inline-block',
                  border: '1px solid',
                  borderRadius: '100%',
                  width: '18px',
                  height: '18px',
                  textAlign: 'center',
                  lineHeight: '16px',
                },
              });
            }
            return this.$createElement('div', {
              style: {
                display: 'flex',
              },
            }, [
              tag,
              quto,
              this.$createElement(Text, { props: {
                textContent: v['name'],
              }, })
            ]);
          },
        },
        {
          label: '任务描述',
          property: 'remark',
          overflow: false,
          align: 'left',
          w: '160px',
          formatter: (v) => {
            return this.$createElement(Text, { props: {
              textContent: v['remark'],
            }, });
          },
        },
        {
          label: '预计工时',
          property: 'planUse',
          w: '78px',
          overflow: true,

          formatter: (v) => {
            if (v['planUse']) {
              return v['planUse'] + '天';
            }
            return '-';
          },
        },
        {
          label: '创建人',
          property: 'createUser',
          w: '70px',
          overflow: true,
          align: 'center',

          formatter: (v) => {
            return member(v['createUser']);
          },
        },
        {
          label: '负责人',
          property: 'principal',
          overflow: true,

          align: 'center',
          w: '70px',
          formatter: (v) => {
            return member(v['principal']);
          },
        },
        {
          overflow: true,
          label: '参与人员',
          property: 'users',
          align: 'left',
          w: '100px',
        },
        {
          label: '开始/截止日期',
          property: 'startTime',
          align: 'center',

          overflow: false,
          w: '145px',
          formatter: (v) => {
            if (!v['startTime'] && !v['endTime']) {
              const val = this.computedMileageSE(v['id'], this.taskList);
              return this.$createElement('div', {}, [
                this.$createElement('p', {
                  domProps: {
                    innerText: val[0],
                  },
                  style: {
                    padding: 0,
                    margin: 0,
                  },
                }),
                this.$createElement('p', {
                  domProps: {
                    innerText: val[1],
                  },
                  style: {
                    padding: 0,
                    margin: 0,

                  },
                })
              ]);
            }
            return this.$createElement('div', {}, [
              this.$createElement('p', {
                domProps: {
                  innerText: moment(v['startTime']).format('YYYY-MM-DD HH:mm'),
                },
                style: {
                  padding: 0,
                  margin: 0,
                },
              }),
              this.$createElement('p', {
                domProps: {
                  innerText: moment(v['endTime']).format('YYYY-MM-DD HH:mm'),
                },
                style: {
                  padding: 0,
                  margin: 0,

                },
              })
            ]);
          },
        },
        {
          label: '进度',
          property: 'totalProgress',
          w: '94px',
          align: 'center',

          overflow: true,
          formatter: (v) => {
            if (v['quoteId']) {
              return '-';
            }
            if (v['totalProgress']) {
              return this.$createElement(processTimeLine, {
                props: {
                  value: v['totalProgress'] + '%',
                  id: v['id'],
                },
              });
            } else {
              return '-';
            }
          },
        },
        {
          label: '附件',
          property: 'file',
          align: 'center',
          w: '70px',
          formatter: (v) => {
            const num = stringifyToArr(v['template']).length;
            return tableCellIconData(icons.file, num, v['template'], Attachment, '附件');
          },
        }
      ];
    },
    renderTableConfig() {
      if (this.isLookTask) {
        return this.tableConfig;
      } else {
        return [
          ...this.tableConfig,
          {
            label: '操作',
            slot: true,
            w: '173px',
            childs: [{
              name: '编辑',
              code: 'edit',
            },
            {
              name: '添加任务',
              code: 'add',
            },
            {
              name: '删除',
              code: 'del',

            }
            ],
          }
        ];
      }
    },
  },
  mounted() {},
  methods: {
    computedMileageSE(id, childList) {
      const theIdList = childList.filter(e => e.parentId === id);
      if (theIdList.length) {
        const timeStartTimeGather = theIdList.map(e => new Date(e.startTime).getTime());
        const timeEndTimeGather = theIdList.map(e => new Date(e.endTime).getTime());
        const minTime = moment(_.min(timeStartTimeGather)).format('YYYY-MM-DD HH:mm');
        const maxTime = moment(_.max(timeEndTimeGather)).format('YYYY-MM-DD HH:mm');
        return [minTime, maxTime];
      }
      return ['-', '-'];
    },

    rowStyle({ row, rowIndex, }) {
      if (row.quoteId === 1) {
        return {
          backgroundColor: '#f7f7f7',
        };
      }
      return {};
    },
    async clickConfirmResult() {
      await ProjectAPI.impose.confirmResult(this.itemCode);
      this.$message.success('提交成功');
      this.$emit('done');
    },
    async successTask() {
      if (this.itemCode) {
        this.SET_TASK_LIST(
          await ProjectAPI.setUp.getTaskList({ itemCode: this.itemCode, })
        );
      }
    },
    clickBackItem() {
      this.$emit('done');
    },
    clickAddMainTask() {
      this.$dialog({
        position: 'center',
        width: dialogWidth.mini_px,
        title: '添加里程碑',
        component: () => (
          <TaskMain isEedit={false} onDone={this.successTask} />
        ),
      });
    },
    clickReferTemplate() {
      this.$dialog({
        position: 'center',
        width: dialogWidth.mini_px,
        title: '引用模板',
        component: () => <ReferTemplate />,
      });
    },
    clickSaveTemplate() {
      this.$dialog({
        width: dialogWidth.mini_px,
        position: 'center',
        title: '保存模板',
        component: () => <SaveTemplate />,
      });
    },
    async getTaskList() {
      if (this.itemCode) {
        this.SET_TASK_LIST(
          await ProjectAPI.setUp.getTaskList({ itemCode: this.itemCode, })
        );
      }
    },
    parentTime(pid, field) {
      const listMap = _.keyBy(this.taskList, 'id');
      return listMap[pid][field];
    },
    options(opt, row) {
      if ('edit/add'.indexOf(opt) > -1) {
        this.taskID = row.id;
        this.taskPID = row.parentId;
      }
      const id = opt === 'edit' ? row.parentId : row.id;
      const start = !row.parentId ? this.time[0] : this.parentTime(id, 'startTime') || this.time[0];
      const end = !row.parentId ? this.time[1] : this.parentTime(id, 'endTime') || this.time[1];
      const startEnd = {
        start,
        end,
      };
      let deleteMessage = '';
      switch (opt) {
        case 'edit':
          this.taskInfo = row;
          if (row.parentId === 0) {
            this.$dialog({
              position: 'center',
              width: dialogWidth.mini_px,
              title: '编辑里程碑',
              component: () => (
                <TaskMain
                  title={'编辑任务'}
                  info={row}
                  isEdit={true}
                  onDone={this.getTaskList}
                />
              ),
            });
          }
          if (row.parentId) {
            this.$innerDialog({
              position: 'center',
              width: dialogWidth.mini_px,
              top: '5vh',
              title: '编辑子任务',
              component: () => (
                <TaskChild
                  title={'编辑任务'}
                  startEnd={startEnd}
                  beforeId={this.beforeId}
                  info={this.taskInfo}
                  id={this.taskID}
                  pId={this.taskPID}
                  maxDay={this.maxDay}
                  onDone={this.getTaskList}
                />
              ),
            });
          }
          break;
        case 'del':
          if (row?.children && row.children.length) {
            deleteMessage = `存在子级任务,是否删除「${row.name}」任务`;
          } else {
            deleteMessage = `是否删除「${row.name}」任务`;
          }
          this.$confirm(deleteMessage, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'customMessageBox',
          }).then(async () => {
            try {
              await ProjectAPI.setUp.deletedTask(row.id);
              this.getTaskList();
              this.$message.success('删除成功');
            } catch (error) {
              this.$message.error(error);
            }
          });

          break;
        case 'add':
          this.taskInfo = {};
          this.maxDay = row.planUse || 100;
          this.beforeId = row.beforeId;
          this.$dialog({
            position: 'center',
            width: dialogWidth.mini_px,
            title: row.parentId ? '添加子任务' : '添加任务',
            top: '5vh',
            component: () => (
              <TaskChild
                title={'添加子任务'}
                startEnd={startEnd}
                beforeId={this.beforeId}
                info={this.taskInfo}
                id={this.taskID}
                pId={this.taskPID}
                maxDay={this.maxDay}
                onDone={this.getTaskList}
              />
            ),
          });
          break;

        default:
          alert('无效的操作');
          break;
      }
    },
  },
};
</script>
<style lang='scss' scoped>
.header {
  &_wrapper {
    display: flex;
    align-items: center;
    &--title {
      font-size: 18px;
      font-weight: 400;
      color: #2d405e;
    }
    &--btngroup {
      display: inline-block;
      margin-left: 36px;
    }
    &--codeName {
      font-size: 18px;
      font-weight: 400;
      color: #879bba;
      display: inline-block;
      margin-left: 36px;
    }
  }
}
.footer {
  &_wrapper {
    display: flex;
    align-items: center;
    padding: 0 !important;
    &-save-button {
      background: #fff;
    }
  }
}
</style>
